package com.mwumz.third.common;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * @Author: wumz
 * @Date: 2020/7/2 14:36
 * @Version 1.0
 */
public class ResponseSerializer extends JsonSerializer<Response> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResponseSerializer.class);

    public ResponseSerializer() {
    }

    @Override
    public void serialize(Response value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("code", value.getCode());
        gen.writeStringField("description", value.getDescription());
        Object data = value.getData();
        if (data instanceof PageResult) {
            gen.writeObjectFieldStart("data");
            gen.writeObjectField("pageIndex", ((PageResult)data).getPageIndex());
            gen.writeObjectField("totalCount", ((PageResult)data).getTotalCount());
            gen.writeObjectField("pageSize", ((PageResult)data).getPageSize());
            gen.writeObjectField("totalPage", ((PageResult)data).getTotalPage());
            gen.writeObjectField("pageData", ((PageResult)data).getPageData());
            Map<String, Object> ext = ((PageResult)data).getExtra();
            ext.forEach((k, v) -> {
                try {
                    gen.writeObjectField(k, v);
                } catch (IOException var4) {
                    LOGGER.error("serialize extra field value failed", var4);
                }

            });
            gen.writeEndObject();
        } else if (data != null) {
            gen.writeFieldName("data");
            serializerProvider.defaultSerializeValue(data, gen);
        }

        gen.writeEndObject();
    }
}
